package com.feiwo.nonego.rpc.proxy.api.future;

import java.io.Serial;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 *
 *
 * @author feiwo 2025-08-08
 */
public class RpcSync extends AbstractQueuedSynchronizer {

    @Serial
    private static final long serialVersionUID = 8788943100427833699L;

    private static final int DONE = 1;
    private static final int PENDING = 0;

    @Override
    protected boolean tryAcquire(int arg) {
        return getState() == DONE;
    }

    @Override
    protected boolean tryRelease(int arg) {
        if (getState() == PENDING) {
            return compareAndSetState(PENDING, DONE);
        }
        return false;
    }

    @Override
    protected boolean tryReleaseShared(int arg) {
        // 将状态设置为DONE
        for (;;) {
            int c = getState();
            if (c == DONE)
                return false;
            if (compareAndSetState(c, DONE))
                return true;
        }
    }

    /**
     * 共享式获取同步状态
     *
     * @param arg 获取参数
     * @return 如果同步状态为DONE返回1，否则返回-1
     */
    @Override
    protected int tryAcquireShared(int arg) {
        // 当状态为DONE时，允许共享获取
        // 返回1表示获取成功，-1表示获取失败
        return getState() == DONE ? 1 : -1;
    }


    public boolean isDone() {
        return getState() == DONE;
    }
}
